//
//  LTNetService.swift
//  myMoya
//
//  Created by xiaoyi on 2020/4/26.
//  Copyright © 2020 lete. All rights reserved.
//

import Foundation
import Moya


// 网络请求结构体
struct LTNetwork {
    
    // 请求成功的回调
    typealias successCallback = (_ result: Any) -> Void
    // 请求失败的回调
    typealias failureCallback = (_ error: MoyaError) -> Void
    
    // 单例
    static let provider = MoyaProvider<LTService>()
    
    // 发送网络请求
    static func request(
        target: LTService,
        success: @escaping successCallback,
        failure: @escaping failureCallback
        ) {
        
        provider.request(target) { result in
            switch result {
            case let .success(moyaResponse):
                do {
                    try success(moyaResponse.mapJSON()) // 测试用JSON数据
                    //做状态码的判断
                    guard let baseModel = NetBaseModel(JSON: (try moyaResponse.mapJSON() as! [String : AnyObject])) else { return }
                    LTLog("网络请求状态: =======>>>>>> \(baseModel.status ?? 0)")
                } catch {
                    failure(MoyaError.jsonMapping(moyaResponse))
                }
            case let .failure(error):
                failure(error)
            }
        }
    }
}


// 定义请求方法
enum LTService {
    case goods(route: String, version: Int)
    case demo2(name: String)
    case demo3
}

extension LTService: TargetType {
    
    // 请求服务器的根路径
    var baseURL: URL { return URL.init(string: "https://www.uaka.com/")! }
    
    // 每个API对应的具体路径
    var path: String {
        switch self {
        case .goods(route: _, version: _):
            return "/api_plus/"
        case .demo2(name: _), .demo3:
            return "/post"
        }
    }
    
    // 各个接口的请求方式，get或post
    var method: Moya.Method {
        switch self {
        case .goods:
            return .get
        case .demo2, .demo3:
            return .post
        }
    }
    
    // 请求是否携带参数，如果需要参数，就做如demo2和demo3的设置
    var task: Task {
        switch self {
        case let .goods(route, version):
            var params: [String: Any] = [:]
                       params["route"] = route
                       params["version"] = version
            // 带有参数,注意前面的let
            return .requestParameters(parameters: params, encoding: URLEncoding.default)
        case let .demo2(name): // 带有参数,注意前面的let
            return .requestParameters(parameters: ["name" : name], encoding: URLEncoding.default)
        case .demo3:
            return .requestPlain // 无参数
            
        }
    }
    
    // 单元测试使用
    var sampleData: Data {
        switch self {
        case .goods, .demo3:
            return "just for test".utf8Encoded
        case .demo2(let name):
            return "{\"name\": \(name)\"}".utf8Encoded
        }
    }
    
    // 请求头
    var headers: [String : String]? {
        return ["Content-type" : "application/json"]
    }
}

// 扩展方法
private extension String {
    var utf8Encoded: Data {
        return data(using: .utf8)!
    }
}



